import requests
import gevent
import time
import matplotlib.pyplot as plt

url = 'http://127.0.0.1:8501/v1/models/half_plus_two:predict'
data = {'instances': [1.0, 2.0, 5.0]}

responseIndex = []  # 记录请求编号
responseTime = []  # 记录对应请求的响应时间
flag = [0]

def getFlag():
    flag[0] = flag[0] + 1
    return flag[0]

def run():
    beginTime = time.time()
    _ = requests.post(url, json=data)#注意，这里的data是字典格式！之所以json=data，是因为请求报文要求入参是json格式，requests模块会自己将data字典转成json格式再发送请求
    endTime = time.time()
    responseTime.append(endTime - beginTime)
    responseIndex.append(getFlag())
    # print('3.1=====', res)
    # print('3.2=====', res.json())

def call_gevent(count):
    """调用gevent 模拟高并发"""
    # begin_time = time.time()
    run_gevent_list = []
    for i in range(count):
        # print('--------------%d--Test-------------' % i)
        run_gevent_list.append(gevent.spawn(run()))
    gevent.joinall(run_gevent_list)
    # end = time.time()
    # print('单次测试时间（平均）s:', (end - begin_time) / count)
    # print('累计测试时间 s:', end - begin_time)


if __name__ == '__main__':
    test_count = 100
    call_gevent(count=test_count)
    # print(responseIndex)
    fig = plt.figure()
    plt.bar(responseIndex, responseTime)
    plt.show()
